/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cslc.consumer;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.alibaba.csp.sentinel.adapter.dubbo.fallback.DubboFallbackRegistry;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.SentinelRpcException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.dubbo.rpc.RpcResult;
import com.cslc.provider.service.ProviderService;

/**
 * Please add the following VM arguments:
 * 
 * <pre>
 * -Djava.net.preferIPv4Stack=true
 * -Dcsp.sentinel.api.port=8721
 * -Dproject.name=dubbo-consumer-demo
 * </pre>
 *
 * @author Eric Zhao
 */
public class DegradeConsumerApp1 {

	private static final String RES_KEY = "com.cslc.provider.service.ProviderService:say(java.lang.String)";

	// private static final String INTERFACE_RES_KEY =
	// "com.alibaba.csp.sentinel.demo.dubbo.FooService";

	@SuppressWarnings("resource")
	public static void main(String[] args) {

		initDegradeRule();
		registerFallback();
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "dubbo-consumer.xml" });
		context.start();
		ProviderService service = context.getBean(ProviderService.class);

		for (int i = 0; i < 15; i++) {
			try {
				String message = service.say("Eric");
				System.out.println("Success: " + message);
			} catch (SentinelRpcException ex) {
				System.out.println("Blocked");
			} catch (Exception ex) {
				//ex.printStackTrace();
				System.out.println("time out");
			}
		}
	}

	private static void initDegradeRule() {
		List<DegradeRule> rules = new ArrayList<DegradeRule>();
		DegradeRule rule = new DegradeRule();
		rule.setResource(RES_KEY);
		// set threshold rt, 10 ms
		rule.setCount(10);
		rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
		rule.setTimeWindow(10);
		rules.add(rule);
		DegradeRuleManager.loadRules(rules);
	}

	private static void registerFallback() {
		// Register fallback handler for consumer.
		// If you only want to handle degrading, you need to
		// check the type of BlockException.
		DubboFallbackRegistry.setConsumerFallback((a, b, ex) -> new RpcResult("Error: " + ex.getClass().getTypeName()));
	}
}
